#!/bin/bash

# Example Holter Deployment Workflow
# This script demonstrates the complete automatic deployment process

set -euo pipefail

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${BLUE}=== Holter Automatic Deployment Workflow ===${NC}"
echo

# Step 1: Initialize the system
echo -e "${YELLOW}Step 1: Initializing the system...${NC}"
cd monitor
go run . migrate
cd ..

cd trode
go build -o trode .
cd ..

echo -e "${GREEN}✅ System initialized${NC}"
echo

# Step 2: Add a test node (you would normally do this via web interface or API)
echo -e "${YELLOW}Step 2: Adding test node to database...${NC}"
echo "Note: In a real scenario, you would add nodes via the web interface or API"
echo "For this example, we'll assume a node with ID 1 exists"
echo -e "${GREEN}✅ Node added (assumed)${NC}"
echo

# Step 3: Bootstrap and auto-deploy
echo -e "${YELLOW}Step 3: Bootstrapping node (with automatic trode deployment)...${NC}"
echo "This will:"
echo "  1. Generate SSH key pair"
echo "  2. Deploy public key using sshpass"
echo "  3. Configure sudoers for passwordless access"
echo "  4. Validate SSH key authentication and sudo access"
echo "  5. Automatically deploy trode if bootstrap is successful"
echo

cd monitor
if go run . bootstrap-node 1; then
    echo -e "${GREEN}✅ Bootstrap and auto-deployment completed successfully!${NC}"
else
    echo -e "${YELLOW}⚠️  Bootstrap completed but auto-deployment may have failed${NC}"
    echo "Check the logs for details"
fi
cd ..

echo

# Step 4: Verify deployment
echo -e "${YELLOW}Step 4: Verifying deployment...${NC}"
cd monitor

# List all nodes with their status
echo "Node status:"
go run . list-nodes

echo

# Check trode status (assuming port 8080)
echo "Checking trode status:"
if go run . status-node 1 8080; then
    echo -e "${GREEN}✅ Trode is running and accessible${NC}"
else
    echo -e "${YELLOW}⚠️  Trode may not be running or accessible${NC}"
fi

echo

# Get recent logs
echo "Recent trode logs:"
go run . logs-node 1 8080 10

cd ..

echo
echo -e "${BLUE}=== Workflow Complete ===${NC}"
echo
echo "The node has been:"
echo "  ✅ Bootstrapped with SSH key authentication"
echo "  ✅ Configured with passwordless sudo access"
echo "  ✅ Automatically deployed with trode monitoring agent"
echo "  ✅ Verified to be running and accessible"
echo
echo "You can now:"
echo "  - Monitor the node via the web dashboard"
echo "  - Manage the trode service (stop/restart/logs)"
echo "  - Add more nodes and repeat the process"
echo
echo "To start the monitoring server:"
echo "  cd monitor && go run . server" 